<template>
    <modal ref="modal_1"
           :title="title"
           :isCloseConfirm="false"
           top="5%"
           width="70%"
           height="50%"
           :close-on-click-modal="true"
           @modalOpened="opened"
           @modalClose="close">
    <div ref="container">
        <div style="padding-left: 35px; padding-top:20px;">
        <el-button @click='zoomOut' ref="zoomOut">缩小</el-button>
        <el-button @click='zoomIn' ref="zoomIn">放大</el-button>
        <el-button @click="expandAll">全部展开</el-button>
        <el-button @click="unExpandAll">全部收起</el-button>

        </div>
        <!--<el-button @click="selectNode">指定选中</el-button>-->
        <div id="jsmind_container" style="width: 100%;height: 80vh;overflow-y: scroll;" ref="jsmindContainer" v-loading="loading"></div>
        <!--<select-work-list ref="selectWorkList" @success="addWorkList"></select-work-list>-->
        <!--<bom-list-form ref="bomListForm" @success="addMaterial"></bom-list-form>-->
        <!--<bom-list-copy ref="bomListCopy" @success="this.refreshJsMind"></bom-list-copy>-->
        <!--<bom-list-edit ref="bomListEdit" @success="this.refreshJsMind"></bom-list-edit>-->
        <!--<bom-list-data ref="bomListData"></bom-list-data>-->
    </div>
    </modal>
</template>

<script>
import { mapGetters } from "vuex";
import '@/styles/jsmind.css'

import { jsmindInit } from '@/utils/jsmind.js'
import { init } from '@/utils/jsmind.menu.js'

import {checkBom, getBomTree,addWorkList, addMaterial,remove,checkBomChild,importBomList, checkBomParent } from "@/api/anwise/material/bom_list";
import {getMaterialByNo } from "@/api/anwise/material/material";
import selectWorkList from "@/views/anwise/material/components/select_work_list.vue";
import bomListForm from "@/views/anwise/material/components/bom_list_form.vue";
import bomListEdit from "@/views/anwise/material/components/bom_list_edit.vue";
import bomListData from "@/views/anwise/material/components/bom_list_data.vue";
import bomListCopy from "@/views/anwise/material/components/bom_list_copy.vue";

export default {
    components: {
        selectWorkList,
        bomListForm,
        bomListEdit,
        bomListData,
        bomListCopy
    },
    data() {
        return {
            title:"Bom结构图",
            selectedNode: '',
            selectedMaterialNo: '',
            isAssign:'',
            form: {},
            query: {},
            loading: true,
            dateFormat: 'YYYY-MM-DD',
            pickerOptions: {},
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0
            },
            search: {},
            selectionList: [],
            option: {
                height: '100%',
                calcHeight: 30,
                tip: false,
                searchShow: true,
                searchMenuSpan: 6,
                border: true,
                index: true,
                labelWidth: 150,
                indexWidth: 100,
                menu: false,
                menuWidth: 120,
                addBtn: false,
                editBtn: false,
                viewBtn: false,
                delBtn: false,
                stripe: true,
                searchIndex: 3,
                searchIcon: false,
                highlightCurrentRow: true,
              searchEnter:true,
                column: [

                    {
                        label: "编号代码",
                        prop: "codeNo",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        rules: [{
                            required: true,
                            message: "请输入编号代码",
                            trigger: "blur"
                        }],
                    },
                    {
                        label: "编号名称",
                        prop: "codeName",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        rules: [{
                            required: true,
                            message: "请输入编号名称",
                            trigger: "blur"
                        }],
                    },
                    {
                        label: "备注",
                        prop: "remark",
                        type: "textarea",
                        overHidden: true,
                        sortable: true,
                        span: 24,
                    },
                    {
                        label: "创建人",
                        prop: "createUserName",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                    },
                    {
                        label: "创建时间",
                        prop: "createTime",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        search: false,
                    },
                ]
            },
            data: [],
            dialogVisible: false,
            mind: {
                meta: {/* 元数据，定义思维导图的名称、作者、版本等信息 */
                    name: 'ztengluo',
                    author: 'hizzgdev@163.com',
                    version: '0.2'
                },
                format: 'node_tree',
                // format: 'node_array',
                data:{},
            },
            jmOptions: {
                container: 'jsmind_container', // [必选] 容器的ID
                editable: true, // [可选] 是否启用编辑
                // theme: 'clouds', // [可选] 主题
                theme: 'primary', // [可选] 主题
                support_html: true,    // 是否支持节点里的HTML元素
                view: {
                    engine: 'canvas',   // 思维导图各节点之间线条的绘制引擎
                    hmargin: 200,        // 思维导图距容器外框的最小水平距离
                    vmargin: 50,         // 思维导图距容器外框的最小垂直距离
                    line_width: 1,       // 思维导图线条的粗细
                    line_color: '#C18AFB'   // 思维导图线条的颜色
                },

            },
            jm: '',

        };
    },
    mounted() {

    },
    methods: {
        showAdd(node) {
            this.selectedNode = node;
            this.$refs.modal_1.show();
        },
        show(title,materialNo) {
          this.selectedMaterialNo = materialNo;
          this.title = title;
          this.loading = true
          this.drawMind()
          getBomTree(this.selectedMaterialNo).then(res => {
                if (res.data.success) {
                    console.log(res.data)
                    this.mind.data = res.data.data[0];
                    this.mind.data.isroot = true;
                    console.log("this.mind", this.mind);
                    if(document.querySelector('.theme-primary')){
                        document.querySelector('.theme-primary').style = 'display:block'
                        document.querySelector('.jsmind').style = 'display:block'
                    }
                    this.jm.show( this.mind);
                    this.loading = false
                    const left = document.querySelector('.theme-primary').getBoundingClientRect().left
                    document.querySelector('.theme-primary').style.transform = 'translateX(-'+left+'px) scale(0.8)';
                    document.querySelector('.jsmind').style.transform = 'translateX(-'+left+'px)  scale(0.8)';
                }
            });

        },
        dblclick(row) {
            console.log(this.selectedNode);
            console.log('@@@@@@@@@@@@@@', row.codeNo, row.codeName, row.id, row);
            let newNode = {
                parentId: this.selectedNode.id,
                codeNo: row.codeNo,
                codeName: row.codeName,
            }
            this.$refs.modal_1.hide();
            addReturn(newNode).then((res) => {
                if (res.data.success) {
                    this.$message({
                        type: "success",
                        message: "添加成功!"
                    });
                    this.jm.select_clear();
                    this.refreshJsMind();

                    // const topic = `<span style="font-size:14px;">[${row.codeNo}]</span><br>${row.codeName}`
                    // const nodeid = new Date().getTime()
                    // this.jm.add_node(this.selectedNode, nodeid, topic)
                    // this.jm.select_node(nodeid);
                    // this.onLoad();
                    this.$emit("success");
                } else {
                    this.$message({
                        type: "error",
                        message: "添加失败!"
                    });
                }
            }, error => {
                window.console.log(error);
            });

        },
        refreshJsMind() {
            getBomTree(this.selectedMaterialNo).then(res => {
                if (res.data.success) {
                    console.log(res.data)
                    this.mind.data = res.data.data[0];
                    this.mind.data.isroot = true;
                    this.jm.show( this.mind);
                }
            });
        },
        addWorkList(data) {
          console.log(data);
          let work = {
              parentNo:this.selectedNode.id,
              nodeNo: data.id
          }
                    addWorkList(work).then(res =>{
                        if (res.data.success) {
                            this.$message({
                                type: "success",
                                message: "添加成功!"
                            });
                            this.jm.select_clear();
                            this.refreshJsMind();
                        }
                    })
        },

        addMaterial(data) {
          console.log(data);
            data.parentNo = this.selectedNode.data.nodeNo;
            addMaterial(data).then(res =>{
                if (res.data.success) {
                    this.$message({
                        type: "success",
                        message: "添加成功!"
                    });
                    this.jm.select_clear();
                    this.refreshJsMind();
                }
            })

        },

        handleDbClick(row) {
            this.selectedMaterialNo = row.materialNo;
            this.isAssign = row.isAssign;
            checkBom(row.materialNo).then(rs => {
                if (rs.data.success) {
                    getBomTree(this.selectedMaterialNo).then(res => {
                        if (res.data.success) {
                            console.log(res.data)
                            this.mind.data = res.data.data[0];
                            this.mind.data.isroot = true;
                            console.log("this.mind", this.mind);
                            if(document.querySelector('.theme-primary')){
                                document.querySelector('.theme-primary').style = 'display:block'
                                document.querySelector('.jsmind').style = 'display:block'
                            }
                            this.jm.show( this.mind);
                            document.querySelector('.theme-primary').style.transform = 'scale(0.8)';
                            document.querySelector('.jsmind').style.transform = 'scale(0.8)';
                        }
                    });
                }
            });
        },
        //获取所有父级id
        findParentIds(dataSource, nodeId) {
            const parentIds = [];
            function traverse(node, nodeId) {
                if (node.id === nodeId) return true;
                if (node.children) {
                    for (const childNode of node.children) {
                        if (traverse(childNode, nodeId)) {
                            parentIds.push(node.id);
                            return true;
                        }
                    }
                }
                return false;
            }
            for (const node of dataSource) {
                if (traverse(node, nodeId)) break;
            }
            return parentIds; // 返回所有父节点ID的数组
        },
        selectNode() {

            this.jm.expand_node(2)
            this.jm.expand_node(88)

            this.jm.select_node(91);
            // this.jm.toggle_node('open2')
        },
        drawMind() {
            init(window)
            jsmindInit(window)
            jsMind.preventMindEventDefault();
            this.jm = new jsMind(this.jmOptions);
        },
        // 缩小
        zoomOut() {
            if(document.querySelector('.theme-primary')){
                let zoom = document.querySelector('.theme-primary').style.transform ? document.querySelector('.theme-primary').style.transform.split('scale')[1].substring(1).split(')')[0] : 0
                let num = zoom - 0.1
                if(num <=0 )  num = 0
                document.querySelector('.theme-primary').style.transform = 'scale('+num+')';
                document.querySelector('.jsmind').style.transform = 'scale('+num+')';
            }
        },
        // 放大
        zoomIn() {
            if(document.querySelector('.theme-primary')){
                let zoom =  document.querySelector('.theme-primary').style.transform ? document.querySelector('.theme-primary').style.transform.split('scale')[1].substring(1).split(')')[0] : 0
                let num = parseFloat(zoom) + 0.1
                if(num >=1)  num = 1
                document.querySelector('.theme-primary').style.transform = 'scale('+num+')';
                document.querySelector('.jsmind').style.transform = 'scale('+num+')';
                const left = document.querySelector('.theme-primary').getBoundingClientRect().left -120
                document.querySelector('.theme-primary').style.transform+= 'translateX(-'+left+'px) ';
                document.querySelector('.jsmind').style.transform+= 'translateX(-'+left+'px) ';
            }
        },
        expandAll() {
            this.jm.expand_all();
        },
        unExpandAll() {
            this.jm.collapse_all();
        },
        downloadImg(){
            this.jm.screenshot.shootDownload()
        },

        // 新增节点
        addNode() {
            var selectedNode = this.jm.get_selected_node() // as parent of new node
            console.log('selected_node', selectedNode)
            if (!selectedNode) { alert('请先选择一个节点'); return }

            var topic = 'new Node'
            this.jm.add_node(selectedNode, 543254354, topic)
            this.dialogVisible = false
        },
        // 删除节点
        onRemoveNode() {
            var selectedId = this.get_selected_nodeid()
            console.log(selectedId)
            if (!selectedId) { alert('请先选择一个节点'); return }
            this.jm.remove_node(selectedId)
        },
        // 获取选中标签的 ID
        get_selected_nodeid() {
            var selectedNode = this.jm.get_selected_node()
            if (selectedNode) {
                return selectedNode.id
            } else {
                return null
            }
        },
        opened() {
            //  this.onLoad(this.page);
        },
        close() {
            // this.clearData();
            // this.clearSelection();
        },
    }
};

</script>

<style>
@keyframes blink {
    0% {
        opacity: 1;
    }

    50% {
        opacity: 0;
    }

    100% {
        opacity: 1;
    }
}

.error {
    animation: blink 3s linear infinite;
    background: red;
}
</style>
